/**
 * 
 */
package cn.ad.server.web.spring.service.ehcache;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;

/**
 * Ehcach辅助类
 * @author Wu Chengjun
 */
@Service
public class EHCacheHelper {

	@Autowired
	EhCacheCacheManager cacheManager;
	
	/**
	 * 根据缓存区标识符获取缓存区Cache对象
	 * @param cacheName 缓存区标识符 
	 * @return
	 */
	private Cache getCache(String cacheName){
		return cacheManager.getCache(cacheName);
	}
	
	/**
	 * 设置缓存
	 * @param cacheName 缓存区标识符
	 * @param key 缓存元素标识
	 * @param value 缓存对象
	 */
	public void setCache(String cacheName, Object key, Object value) {
		Cache cache = getCache(cacheName);
		if(cache != null){
			cache.put(key, value);
		}
	}

	/**
	 * 根据传入参数KEY从指定缓存区中获取缓存对象
	 * 
	 * @param cacheName 缓存区标识符
	 * @param key 缓存元素标识
	 * @param type 缓存对象类型
	 * @return
	 */
	public <T> T getCache(String cacheName, Object key, Class<T> type) {
		Cache cache = getCache(cacheName);
		if(cache != null){
			return cache.get(key, type);
		}
		return null;
	}

	/**
	 * 根据缓存元素标识从缓存区中移除元素
	 * @param cacheName 缓存标识符
	 * @param key 元素标识
	 */
	public void rmCache(String cacheName, String key) {
		Cache cache = getCache(cacheName);
		if(cache != null){
			cache.evict(key);
		}
	}
	
	/**
	 * 清理缓存区中的所有元素
	 * @param cacheName 缓存区标识符
	 */
	public void clearCache(String cacheName){
		Cache cache = getCache(cacheName);
		if(cache != null){
			cache.clear();
		}
	}
}
